package com.farina.tracescleaner;

import com.farina.tracescleaner.tasks.DeleteAppDataTask;
import com.farina.tracescleaner.tasks.DeleteBrowserDataTask;
import com.farina.tracescleaner.tasks.DeleteCallLogTask;
import com.farina.tracescleaner.tasks.DeleteSMSTask;
import com.farina.tracescleaner.tasks.DeleteWhatsAppDataTask;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Binder;
import android.os.IBinder;
import android.os.Looper;


public class ControlService extends Service{
	
	public static Thread controlThread; //Thread that implement the polling
	public static boolean isCtrlActive=false;
	public static Notifier notifier=null;

	public static Context service;

	private Runnable controlTask = new Runnable() {

		@Override
		public void run() {
			Looper.prepare();
			while (isCtrlActive) {
				SharedPreferences settings = getSharedPreferences(MainActivity.STARTUP_DATA, 0);
				boolean call = settings.getBoolean("callCanc", false);
				boolean sms = settings.getBoolean("smsCanc", false);
				boolean appData = settings.getBoolean("appDataCanc", false);
				boolean browserData = settings.getBoolean("browserDataCanc", false);
				boolean whatsappData = settings.getBoolean("whatsappDataCanc", false);
				
				if(call){
					new DeleteCallLogTask(service).delete();
					System.out.println("1");
				}
				if(sms){
					new DeleteSMSTask(service).delete();
					System.out.println("2");
				}
				if(appData){
					new DeleteAppDataTask(service).delete();
					System.out.println("3");
				}
				if(browserData){
					new DeleteBrowserDataTask(service).delete();
					System.out.println("3");
				}
				if(whatsappData){
					new DeleteWhatsAppDataTask(service).delete();
					System.out.println("3");
				}
				
			
				
				try {
				    int period = settings.getInt("ctrlTimePeriod", 10000);
					Thread.sleep(period);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}

		}

	};
	

	@Override
	public void onCreate() {
		controlThread = new Thread(controlTask, "CtrlService");
		isCtrlActive=true;
		controlThread.start();
		notifier=new Notifier(this);
		notifier.mainNotification();
		service=this;
	}

	@Override
	public void onDestroy() {
		isCtrlActive=false;
		notifier.destroyMainNotify();
	}

	public class LocalBinder extends Binder {
		ControlService getService() {
			return ControlService.this;
		}
	}

	@Override
	public IBinder onBind(Intent arg0) {
		return new LocalBinder();
	}
}
